package com.hifar.utils;

// 构建正则表达式，转义关键字中的特殊字符
import java.util.*;
import java.util.regex.*;

public class MultiKeywordReplacer {
    public static String replaceMultiple(String input, Map<String, String> replacements) {
        if (input == null || input.isEmpty() || replacements == null || replacements.isEmpty()) {
            return input;
        }

        // 按关键字长度降序排序，确保长关键字优先匹配
        List<String> keys = new ArrayList<>(replacements.keySet());
        keys.sort((a, b) -> Integer.compare(b.length(), a.length()));

        // 构建正则表达式，转义特殊字符
        String regex = "(" + String.join("|", keys.stream().map(Pattern::quote).toArray(String[]::new)) + ")";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String matched = matcher.group(1);
            String replacement = replacements.getOrDefault(matched, matched);
            // 转义替换值中的特殊字符
            matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
        }
        matcher.appendTail(result);

        return result.toString();
    }

    public static void main(String[] args) {
        Map<String, String> replacements = new HashMap<>();
        replacements.put("苹果", "橘子");
        replacements.put("香蕉", "葡萄");
        replacements.put("橘子", "梨");

        String input = "苹果 香蕉 橘子 习惯 西瓜";
        String output = replaceMultiple(input, replacements);
        System.out.println(output); // 输出：橘子 葡萄 梨
    }
}